<template>
  <div class="user-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">
        <i class="el-icon-user"></i>
        个人中心
      </h2>
      <p class="page-description">查看和编辑您的个人信息</p>
    </div>

    <el-row :gutter="20">
      <!-- 左侧：头像和基本信息 -->
      <el-col :span="8">
        <el-card class="profile-card">
          <div slot="header" class="card-header">
            <span><i class="el-icon-picture"></i> 头像设置</span>
          </div>

          <div class="avatar-section">
            <div class="avatar-container">
              <img
                :src="currentAvatar"
                :alt="userInfo.name"
                class="avatar-image"
                @error="handleAvatarError"
              >
              <div class="avatar-overlay" @click="showAvatarDialog = true">
                <i class="el-icon-camera"></i>
                <span>更换头像</span>
              </div>
            </div>

            <div class="user-basic-info">
              <h3>{{ userInfo.name || '未设置' }}</h3>
              <div class="user-type">
                <el-tag :type="getUserTypeTag(userInfo.type)" size="medium">
                  {{ getUserTypeText(userInfo.type) }}
                </el-tag>
              </div>
              <p class="user-id">ID: {{ userInfo.id || '-' }}</p>
            </div>
          </div>
        </el-card>

        <!-- 系统信息卡片 -->
        <el-card class="info-card">
          <div slot="header" class="card-header">
            <span><i class="el-icon-info"></i> 系统信息</span>
          </div>
          <div class="info-content">
            <div class="info-item">
              <i class="el-icon-info"></i>
              <span class="label">系统版本：</span>
              <span class="value">v1.0.0</span>
            </div>
            <div class="info-item">
              <i class="el-icon-monitor"></i>
              <span class="label">浏览器：</span>
              <span class="value">{{ browserInfo }}</span>
            </div>
            <div class="info-item">
              <i class="el-icon-time"></i>
              <span class="label">最后登录：</span>
              <span class="value">{{ userInfo.lastLoginTime || '首次登录' }}</span>
            </div>
            <div class="info-item">
              <i class="el-icon-location"></i>
              <span class="label">登录IP：</span>
              <span class="value">{{ userInfo.lastLoginIp || '未知' }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧：详细信息 -->
      <el-col :span="16">
        <el-card class="info-card">
          <div slot="header" class="card-header">
            <span><i class="el-icon-edit"></i> 个人信息</span>
            <el-button type="text" @click="editMode = !editMode">
              {{ editMode ? '取消编辑' : '编辑信息' }}
            </el-button>
          </div>

          <div class="info-content">
            <el-form :model="form" :rules="rules" ref="profileForm" label-width="120px">
              <el-form-item label="用户名称" prop="name">
                <el-input
                  v-model="form.name"
                  :disabled="!editMode"
                  placeholder="请输入用户名称"
                ></el-input>
              </el-form-item>

              <el-form-item label="手机号码" prop="phone">
                <el-input
                  v-model="form.phone"
                  :disabled="!editMode"
                  placeholder="请输入手机号码"
                ></el-input>
              </el-form-item>

              <el-form-item label="邮箱地址" prop="email">
                <el-input
                  v-model="form.email"
                  :disabled="!editMode"
                  placeholder="请输入邮箱地址"
                ></el-input>
              </el-form-item>

              <el-form-item label="用户类型" v-if="!editMode">
                <el-tag :type="getUserTypeTag(userInfo.type)">
                  {{ getUserTypeText(userInfo.type) }}
                </el-tag>
              </el-form-item>

              <el-form-item label="身份证号" v-if="userInfo.idNo && !editMode">
                <span class="info-text">{{ maskIdCard(userInfo.idNo) }}</span>
              </el-form-item>

              <el-form-item label="地址信息" v-if="userInfo.address && !editMode">
                <span class="info-text">{{ userInfo.address }}</span>
              </el-form-item>

              <el-form-item label="创建时间" v-if="!editMode">
                <span class="info-text">{{ userInfo.createTime }}</span>
              </el-form-item>

              <el-form-item v-if="editMode">
                <el-button type="primary" @click="saveProfile" :loading="saving">
                  保存修改
                </el-button>
                <el-button @click="resetForm">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
        <!-- 修改密码卡片 -->
        <el-card class="password-card">
          <div slot="header" class="card-header">
            <span><i class="el-icon-lock"></i> 修改密码</span>
            <el-button type="text" @click="showPasswordReset">
              点击修改密码
            </el-button>
          </div>

          <div class="password-tips">
            <el-alert
              title="安全提示"
              type="info"
              description="为了您的账户安全，建议定期更换密码，密码长度6-20位。"
              :closable="false"
              show-icon
            ></el-alert>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 头像上传对话框 -->
    <el-dialog
      title="更换头像"
      :visible.sync="showAvatarDialog"
      width="500px"
      :close-on-click-modal="false"
      custom-class="action-dialog"
    >
      <div class="avatar-upload">
        <div class="upload-area">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            accept="image/*"
          >
            <img v-if="tempAvatar" :src="tempAvatar" class="avatar-preview">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <p class="upload-tip">点击上传头像，支持 JPG、PNG 格式，大小不超过2MB</p>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAvatarDialog = false">取消</el-button>
        <el-button type="primary" @click="saveAvatar" :disabled="!tempAvatar">确定</el-button>
      </div>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <PasswordReset
      :visible.sync="passwordResetVisible"
      :user-name="userInfo.name"
      :show-code="false"
      @success="handlePasswordResetSuccess"
    />
  </div>
</template>

<script>
import { getCurrentUser, updateUserInfo } from '@/api/aggregation'
import PasswordReset from '@/components/PasswordReset'
import { getToken } from '@/utils/auth'

export default {
  name: 'UserManagement',
  components: {
    PasswordReset
  },
  data() {
    return {
      loading: false,
      saving: false,
      editMode: false,
      passwordResetVisible: false,
      showAvatarDialog: false,
      tempAvatar: '',
      defaultAvatar: require('@/assets/images/profile.jpg'),

      userInfo: {
        id: null,
        name: '',
        phone: '',
        email: '',
        deptName: '',
        type: null,
        createTime: '',
        lastLoginTime: '',
        lastLoginIp: '',
        avatar: ''
      },

      form: {
        name: '',
        phone: '',
        email: ''
      },

      rules: {
        name: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    browserInfo() {
      const ua = navigator.userAgent
      if (ua.indexOf('Chrome') > -1) return 'Chrome'
      if (ua.indexOf('Firefox') > -1) return 'Firefox'
      if (ua.indexOf('Safari') > -1) return 'Safari'
      if (ua.indexOf('Edge') > -1) return 'Edge'
      return 'Unknown'
    },
    uploadUrl() {
      return process.env.VUE_APP_BASE_API + '/agg/file/upload'
    },
    uploadHeaders() {
      return {
        'token': getToken()
      }
    },
    // 从 Vuex store 中获取头像，保证全局同步
    currentAvatar() {
      return this.$store.state.user.avatar || this.userInfo.avatar || this.defaultAvatar
    }
  },
  mounted() {
    this.loadUserInfo()
  },
  methods: {
    // 加载用户信息
    async loadUserInfo() {
      this.loading = true
      try {
        const userId = this.$store.state.user.id
        Logger.log('准备调用getCurrentUser，userId:', userId)

        // 检查userId是否有效
        if (!userId) {
          Logger.log('⚠️ 用户ID为空，跳过getCurrentUser调用')
          this.userInfo = {}
          return
        }

        const response = await getCurrentUser()
        if (response.code === 0 && response.data) {
          this.userInfo = { ...this.userInfo, ...response.data }
          this.form = {
            name: this.userInfo.name || '',
            phone: this.userInfo.phone || '',
            email: this.userInfo.email || ''
          }

          // 同步头像到 Vuex store
          if (this.userInfo.avatar) {
            this.$store.commit('SET_AVATAR', this.userInfo.avatar)
          }

          Logger.log('✅ 用户信息加载成功:', this.userInfo)
        } else {
          this.userInfo = {}
        }
      } catch (error) {
        Logger.error('加载用户信息失败:', error)
        this.userInfo = {}
      } finally {
        this.loading = false
      }
    },

    // 保存个人信息
    async saveProfile() {
      try {
        await this.$refs.profileForm.validate()
        this.saving = true

        const updateData = {
          id: this.userInfo.id,
          name: this.form.name,
          phone: this.form.phone,
          email: this.form.email,
          avatar: this.userInfo.avatar
        }

        Logger.log('更新用户信息:', updateData)
        const response = await updateUserInfo(updateData)

        if (response.code === 0) {
          this.$message.success('个人信息更新成功')
          this.userInfo = { ...this.userInfo, ...this.form }
          this.editMode = false
          // 重新加载用户信息
          await this.loadUserInfo()
        } else {
          this.$message.error(response.msg || '更新失败')
        }
      } catch (error) {
        Logger.error('更新用户信息失败:', error)
        if (error !== false) { // 验证失败会返回false
          this.$message.error('更新失败，请重试')
        }
      } finally {
        this.saving = false
      }
    },

    // 重置表单
    resetForm() {
      this.form = {
        name: this.userInfo.name || '',
        phone: this.userInfo.phone || '',
        email: this.userInfo.email || ''
      }
      this.editMode = false
    },

    // 头像上传前验证
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
        return false
      }
      return true
    },

    // 头像上传成功
    handleAvatarSuccess(response, file) {
      Logger.log('头像上传响应:', response)
      if (response && response.code === 0) {
        this.tempAvatar = response.data
      } else {
        this.$message.error(response?.msg || '头像上传失败')
      }
    },

    // 保存头像
    async saveAvatar() {
      if (!this.tempAvatar) return

      try {
        this.saving = true

        // 更新用户信息中的头像
        const updateData = {
          id: this.userInfo.id,
          name: this.userInfo.name,
          phone: this.userInfo.phone,
          email: this.userInfo.email,
          avatar: this.tempAvatar
        }

        const response = await updateUserInfo(updateData)

        if (response.code === 0) {
          // 1. 更新本地userInfo
          this.userInfo.avatar = this.tempAvatar

          // 2. 更新全局Vuex store中的头像
          this.$store.commit('SET_AVATAR', this.tempAvatar)

          Logger.log('✅ 头像更新成功，已同步到全局状态')
          this.$message.success('头像更新成功')
          this.showAvatarDialog = false
          this.tempAvatar = ''
        } else {
          this.$message.error(response.msg || '头像更新失败')
        }
      } catch (error) {
        Logger.error('头像更新失败:', error)
        this.$message.error('头像更新失败')
      } finally {
        this.saving = false
      }
    },

    // 头像加载错误处理
    handleAvatarError() {
      Logger.log('头像加载失败，使用默认头像')
    },

    // 获取用户类型文本
    getUserTypeText(type) {
      const typeMap = {
        1: 'C端用户',
        2: '业务员',
        3: '商家',
        4: '区域代理',
        5: '总公司'
      }
      return typeMap[type] || '未知类型'
    },

    // 获取用户类型标签
    getUserTypeTag(type) {
      const tagMap = {
        1: 'info',
        2: 'success',
        3: 'warning',
        4: 'primary',
        5: 'danger'
      }
      return tagMap[type] || 'info'
    },

    // 遮罩身份证号
    maskIdCard(idCard) {
      if (!idCard) return '未设置'
      if (idCard.length < 8) return idCard
      return idCard.substring(0, 4) + '****' + idCard.substring(idCard.length - 4)
    },

    showPasswordReset() {
      this.passwordResetVisible = true
    },

    handlePasswordResetSuccess() {
      this.$message.success('密码修改成功，请重新登录')
      // 可以选择是否自动退出登录
      setTimeout(() => {
        this.$store.dispatch('FedLogOut').then(() => {
          // 使用 window.location.replace 强制刷新页面并跳转到登录页
          window.location.replace('/aggregation-login')
        })
      }, 2000)
    }
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  color: #303133;
  font-size: 24px;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
}

.page-description {
  color: #606266;
  margin: 0;
  font-size: 14px;
}

.profile-card,
.info-card,
.password-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.card-header i {
  margin-right: 5px;
}

.avatar-section {
  text-align: center;
  padding: 10px;
}

.avatar-container {
  position: relative;
  display: inline-block;
  margin-bottom: 20px;
}

.avatar-image {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.avatar-overlay i {
  font-size: 24px;
  margin-bottom: 4px;
}

.avatar-overlay span {
  font-size: 12px;
}

.user-basic-info h3 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 20px;
}

.user-type {
  margin: 8px 0;
  display: flex;
  justify-content: center;
}

.user-id {
  color: #909399;
  font-size: 12px;
  margin: 0;
}

.info-content {
  padding: 10px 0;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  font-size: 14px;
  padding: 8px 12px;
  background: #f9f9f9;
  border-radius: 4px;
}

.info-item i {
  margin-right: 10px;
  color: #409EFF;
  width: 20px;
}

.info-item .label {
  font-weight: bold;
  color: #666;
  min-width: 80px;
}

.info-item .value {
  color: #333;
  flex: 1;
}

.info-text {
  color: #606266;
}

.password-tips {
  padding: 10px 0;
}

.avatar-upload {
  text-align: center;
}

.avatar-uploader {
  display: inline-block;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader-icon:hover {
  border-color: #409eff;
}

.avatar-preview {
  width: 178px;
  height: 178px;
  object-fit: cover;
  border-radius: 6px;
}

.upload-tip {
  color: #606266;
  font-size: 12px;
  margin-top: 8px;
}

/* 响应式设计 */
@media screen and (max-width: 1200px) {
  .page-title {
    font-size: 20px;
  }

  .avatar-image {
    width: 100px;
    height: 100px;
  }
}
</style>
